package com.hzp.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzp.entity.Organization;
import com.hzp.dao.OrganizationDao;
import com.hzp.service.OrganizationService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 组织机构表(Organization)表服务实现类
 *
 * @author makejava
 * @since 2021-06-29 19:24:44
 */
@Service("organizationService")
public class OrganizationServiceImpl implements OrganizationService {
    @Resource
    private OrganizationDao organizationDao;

    /**
     * 通过ID查询单条数据
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Organization findById(Integer id) {
        return this.organizationDao.selectById(id);
    }

    /**
     * 查询多条数据
     * @param pageNum 当前页码
     * @param pageSize  查询条数
     * @return 对象列表
     */
    @Override
    public Map<String,Object> findPage(Integer pageNum, Integer pageSize,Organization organization) {
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<Organization> pageInfo = new PageInfo<>(organizationDao.selectAll(organization));
        Map<String,Object> map = new HashMap<>();
        map.put("list",pageInfo.getList());
        map.put("pages",pageInfo.getPages());
        map.put("total",pageInfo.getTotal());
        return map;
    }

    /**
     * 查询所有数据
     * @return 对象列表
     */
    @Cacheable(value = "organization:cache")
    @Override
    public List<Organization> findAll() {
        return organizationDao.selectAll(new Organization());
    }

    /**
     * 新增数据
     * @param organization 实例对象
     * @return 实例对象
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "organization:cache",allEntries = true)
    @Override
    public Organization add(Organization organization) {
        this.organizationDao.insert(organization);
        return organization;
    }

    /**
     * 修改数据
     * @param organization 实例对象
     * @return 实例对象
     */
    @Override
    public Organization edit(Organization organization) {
        this.organizationDao.update(organization);
        return this.findById(organization.getId());
    }

    /**
     * 通过主键删除数据
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean remove(Integer id) {
        return this.organizationDao.deleteById(id) > 0;
    }

    /**
     * 批量删除
     * @param id 主键数组
     * @return 是否成功
     */
    @Override
    public boolean removeBatch(Integer[] id) {
        for (Integer i:id) {
            this.remove(i);
        }
        return true;
    }
}
